<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'db/db_connection.class.php');


require_once('tree_menu.class.php');
require_once('tree_menu_item_dbc.class.php');

require_once('te_tree_menu_dbc_import_file_failed.class.php');


class Tree_Menu_DBC extends Tree_Menu {
	private $table;

	function __construct($table = 'menu') {
		$this->set_table($table);
	}


	public function set_table($table) {
		$this->table = $table;
	}


	public function get_table() {
		return $this->table;
	}


	public function load_menu(DB_Connection $dbc) {
		$table = addslashes($this->get_table());

		$sql = "select id from $table where parent = 0 order by `order` asc";
		$rez = $dbc->execute($sql);
		while ($rez_obj = $rez->fetch_object()) {
			$item = new Tree_Menu_Item_DBC($this->get_table());
			$item->load_by_id($dbc, $rez_obj->ID);
			$this->add_item(clone $item);
		}
	}


	public function save(DB_Connection $dbc) {
		foreach($this->items as $item) {
			$item->save($dbc);
		}
	}


	public function find_item($parent_hid) {
		$ret = false;

		foreach($this->items as $item) {
			$rez = $this->search_for_hid($item, $parent_hid);
			if ($rez) {
				$ret = $rez;
				break;
			}
		}

		return $ret;
	}


	public function search_for_hid(Tree_Menu_Item_DBC $item, $hid) {
		$ret = false;

		if ($item->get_hid() == $hid) {
			$ret = $item;
		} else {
			$subitems = $item->get_subitems();
			foreach($subitems as $s) {
				$rez = $this->search_for_hid($s, $hid);
				if ($rez) {
					$ret = $rez;
					break;
				}
			}
		}

		return $ret;
	}


	public function add_item(Tree_Menu_Item $item) {
		if ($item instanceof Tree_Menu_Item_DBC) {
			parent::add_item($item);
		} else {
			throw new TE_Tree_Menu('$item is not instance of Tree_Menu_Item_DBC');
		}
	}


	public function update_item(Tree_Menu_Item_DBC $item) {
		if ($this->item_exists($item)) {
			$item_orig = $this->items[$item->get_hid()];
			$id = $item_orig->get_id();
			$subitems = $item_orig->get_subitems();
			$item->set_id($id);
			$item->set_subitems($subitems);
			$this->items[$item->get_hid()] = $item;
		} else {
			throw new TE_Tree_Menu('Such item does not exists: '.$item->get_label());
		}
	}
}